package com.deer.wms.base.system.web.task;

import com.deer.wms.base.system.finalUtil.BoxInfoState;
import com.deer.wms.base.system.finalUtil.TaskInfoState;
import com.deer.wms.base.system.model.BillInRecord;
import com.deer.wms.base.system.model.bill.BillInDetail;
import com.deer.wms.base.system.model.bill.BillOutDetail;
import com.deer.wms.base.system.model.box.BoxInfo;
import com.deer.wms.base.system.model.box.BoxItem;
import com.deer.wms.base.system.model.task.TaskInfo;
import com.deer.wms.base.system.model.task.TaskInfoCriteria;
import com.deer.wms.base.system.model.task.TaskInfoDto;
import com.deer.wms.base.system.model.ware.CellInfo;
import com.deer.wms.base.system.service.BillInRecordService;
import com.deer.wms.base.system.service.bill.IBillInDetailService;
import com.deer.wms.base.system.service.bill.IBillInMasterService;
import com.deer.wms.base.system.service.box.BoxInfoService;
import com.deer.wms.base.system.service.box.BoxItemRecordService;
import com.deer.wms.base.system.service.box.IBoxItemService;
import com.deer.wms.base.system.service.task.BillInTaskInfoService;
import com.deer.wms.base.system.service.task.ITaskInfoService;
import com.deer.wms.base.system.service.task.TaskInfoHistoryService;
import com.deer.wms.base.system.service.ware.ICellInfoService;
import com.deer.wms.base.system.util.DateUtil;
import com.deer.wms.common.core.controller.BaseController;
import com.deer.wms.common.core.domain.AjaxResult;
import com.deer.wms.common.core.page.TableDataInfo;
import com.deer.wms.common.core.result.CommonCode;
import com.deer.wms.common.core.result.Result;
import com.deer.wms.common.core.result.ResultGenerator;
import com.deer.wms.framework.util.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/***
 *入库任务
 * @author 李帅辰
 * @date 2020/10/12 15:06
 * @return 
 */
@Controller
@Slf4j
@RequestMapping("/in/billlIntaskInfo")
public class BillInTaskInfoConterller  extends BaseController {
    @Autowired
    private IBillInMasterService billInMasterService;
    @Autowired
    private ITaskInfoService taskInfoService;
    @Autowired
    private BillInTaskInfoService billInTaskInfoService;

    @Autowired
    private TaskInfoHistoryService taskInfoHistoryService;
    @Autowired
    private IBoxItemService boxItemService;
    @Autowired
    private IBillInDetailService billInDetailService;
    @Autowired
    private BoxInfoService boxInfoService;
    @Autowired
    private ICellInfoService cellInfoService;
    @Autowired
    private BillInRecordService billInRecordService;
    @Autowired
    private BoxItemRecordService boxItemRecordService;
    private String prefix = "task";

    @RequiresPermissions("in:task:view")
    @GetMapping()
    public String taskInfo() {
        return prefix + "/billlIntaskInfo";
    }


    /***
     *查询入库任务列表
     * @param taskInfoCriteria
     * @author 李帅辰
     * @date 2020/9/29 17:50
     * @return com.deer.wms.common.core.page.TableDataInfo
     */
    @PostMapping("/billInFindList")
    @ResponseBody
    public TableDataInfo billInFindList(TaskInfoCriteria taskInfoCriteria) {
        startPage();
        List<TaskInfoDto> list = billInTaskInfoService.billInFindList(taskInfoCriteria);
        return getDataTable(list);
    }

    @PostMapping("resetTaskInCellInfo")
    @ResponseBody
    public Result reSetCellInfo(int id){
        TaskInfo taskInfo = billInTaskInfoService.selectTaskInfoById(id);
//        TaskInfo moveTaskInfo = taskInfoService.selectTaskInfoById(id);
//        if (null == taskInfo && null == moveTaskInfo){
//            return ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR, "false");
//        }
//        TaskInfo entity = Objects.isNull(taskInfo) ? moveTaskInfo : taskInfo;
        // 重新分配货位，在redis中做标记，WCS跟据标记重新分配货位并下发
        boolean res = billInTaskInfoService.reSetCellInfo(taskInfo);
        if (res){
            return ResultGenerator.genSuccessResult();
        }
        return ResultGenerator.genFailResult(CommonCode.SERVER_INERNAL_ERROR);
    }

    /***
     *入库任务作废
     * @author 李帅辰
     * @date 2020/10/12 17:31 
     * @return com.deer.wms.common.core.domain.AjaxResult
     */
    @PostMapping("/billInTaskInvalid")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result billInTaskInvalid(int id) {
        TaskInfo taskInfo = billInTaskInfoService.selectTaskInfoById(id);
        Integer state = taskInfo.getState();
        if(state== TaskInfoState.STATE_ZERO){
        String createUserName = ShiroUtils.getLoginName();
        taskInfo.setCreateUserName(createUserName);
        taskInfo.setState(5);//作废状态
        int editTask= billInTaskInfoService.updateTaskInfo(taskInfo);
        //挪到任务历史表
        int saveTaskHis=taskInfoHistoryService.saveTaskInfoHistory(taskInfo);
        int deTask= billInTaskInfoService.deleteTaskInfoById(id);
            BoxInfo boxInfo = new BoxInfo();
            boxInfo.setBoxState(BoxInfoState.BOXINFO_STATE_ZERO);
            //boxInfo.setBoxCode(taskInfo.getBoxCode());
            int editBoxInfo = boxInfoService.updateBoxInfo(boxInfo);
            if(editTask==0||saveTaskHis==0||deTask==0||editBoxInfo==0){
                try {
                    log.error("作废入库任务方法执行出错，回滚");
                    throw new Exception("error--作废入库任务方法执行出错，手动抛异常");
                } catch (Exception e) {
                    e.printStackTrace();
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
                if(editTask==0){
                    return ResultGenerator.genFailResult(CommonCode.EDITTASKINFO_ERROR, "false");
                }else if(saveTaskHis==0){
                    return ResultGenerator.genFailResult(CommonCode.SAVETASKINFOHISTORY_ERROR, "false");
                }else if(deTask==0){
                    return ResultGenerator.genFailResult(CommonCode.DETASKINFO_ERROR, "false");
                }
            }
             return ResultGenerator.genSuccessResult();
        }
        return ResultGenerator.genFailResult(CommonCode.TASKINFO_STATE, "false");
    }
    
  /***
   *入库强制完成
   * @author 李帅辰
   * @date 2020/10/12 18:05 
   * @return com.deer.wms.common.core.domain.AjaxResult
   */
    @PostMapping("/billInForceComplete")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result billInForceComplete(int id) {
        TaskInfoDto taskInfoDto = billInTaskInfoService.selectTaskInfoByid(id);
        Integer cellId = taskInfoDto.getCellId();//货位IDs
        BoxItem boxItem = new BoxItem();
        BoxInfo boxInfo = new BoxInfo();
        BillInRecord billInRecord = new BillInRecord();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date time = null;
        try {
            //time = DateUtil.timeAddByDays(sdf.parse(taskInfoDto.getPdTime()), taskInfoDto.getDateWarning());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String expTime = sdf.format(time);
        billInRecord.setExp(expTime);//计算预计的过期时间
        //boxItem.setExp(expTime);//计算预计的过期时间
        //更新明细的入库数量
        BillInDetail billInDetail = new BillInDetail();
        billInDetail.setBillInDetailId(taskInfoDto.getBillInDetailId());//ID
        //billInDetail.setQuantityReceived(taskInfoDto.getQuantity());//数量
        int editBill = billInDetailService.updateBillInInfo(billInDetail);
        //更新库存
        //boxItem.setQuantity(taskInfoDto.getQuantity());
        //boxItem.setBoxCode(taskInfoDto.getBoxCode());
        boxItem.setBatch(taskInfoDto.getBatch());
        //boxItem.setItemCode(taskInfoDto.getItemCode());
        boxItem.setBillInDetailId(taskInfoDto.getBillInDetailId());
        //boxItem.setPd(taskInfoDto.getPdTime());
        boxItem.setWareId(1220);
        int saveBoxItem = boxItemService.insertBoxItem(boxItem);
        //更新托盘状态
        //boxInfo.setBoxCode(taskInfoDto.getBoxCode());
        boxInfo.setBoxState(1);//0-不在货位 1-货位上  2-任务中
        boxInfo.setHasGoods(1);//   0-无货 1-有货
        boxInfo.setBoxCellId(cellId);//货位
        boxInfo.setBoxType(2);//类型：1-料箱  2-托盘
        int editBoxInfo = boxInfoService.updateBoxInfo(boxInfo);
        //货位以及状态 cellInfo
        CellInfo cellInfo = new CellInfo();
        cellInfo.setState(1);//状态  ：0-无托盘；1-有货；2-出库中；3-入库中；4故障
        cellInfo.setCellId(cellId);
        int editCellInfo = cellInfoService.updateCellInfo(cellInfo);
        //任务历史表
        //修改
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setState(6);//强制完成状态
        taskInfo.setId(taskInfoDto.getId());
        int editTaskInfo = billInTaskInfoService.updateTaskInfo(taskInfo);
        int saveTaskInfoHistory =  taskInfoHistoryService.saveTaskInfoHistory(billInTaskInfoService.selectTaskInfoById(taskInfoDto.getId()));
        int de = billInTaskInfoService.deleteTaskInfoById(taskInfoDto.getId());//删除已完成的任务表
        //同步入库报表
        billInRecord.setBillInDetailId(taskInfoDto.getBillInDetailId());//出库单id
        //billInRecord.setAcceptQuantity(taskInfoDto.getQuantity());//入库数量
        //billInRecord.setBoxCode(taskInfoDto.getBoxCode());
        //billInRecord.setBarCode(taskInfoDto.getBarCode());
        //billInRecord.setPd(taskInfoDto.getPdTime());
        billInRecord.setBatch(taskInfoDto.getBatch());
        int saveBillInRecord = billInRecordService.insertBillInRecord(billInRecord);
        //同步到库存记录表：
        //int re6 = boxItemRecordService.insertBoxItemRecord(boxItem);
        if (editBill==0 || saveBoxItem==0 || editBoxInfo==0 || de==0||editCellInfo==0||editTaskInfo==0||saveTaskInfoHistory==0){
            log.error("入库成功后的更新操作失败了,回滚！！！！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            if(editBill==0){
                return ResultGenerator.genFailResult(CommonCode.EDITBILLOUT_ERROR, "false");
            }else if( saveBoxItem==0){
                return ResultGenerator.genFailResult(CommonCode.BOXITEM_ERROR, "false");
            }else if(editBoxInfo==0){
                return ResultGenerator.genFailResult(CommonCode.BXOINFO_EDITERROR, "false");
            }else if(editCellInfo==0){
                return ResultGenerator.genFailResult(CommonCode.CELLINFO_ERROR, "false");
            }else if(editTaskInfo==0){
                return ResultGenerator.genFailResult(CommonCode.EDITTASKINFO_ERROR, "false");
            }else if(saveTaskInfoHistory==0){
                return ResultGenerator.genFailResult(CommonCode.SAVETASKINFOHISTORY_ERROR, "false");
            }else if(de==0){
                return ResultGenerator.genFailResult(CommonCode.DETASKINFO_ERROR, "false");
            }
        }
        return ResultGenerator.genSuccessResult();
    }
    
    
}
